package asa;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import forum.ForumPost;

public class PostBucket {

	private Queue<List<ForumPost>> posts;
	private int buffer;
	private int threads;
	private int finished;

	public PostBucket(int bufferSize, int threads) {
		posts = new LinkedList<List<ForumPost>>();
		this.buffer = bufferSize;
		this.threads = threads;
	}

	public synchronized void addPost(List<ForumPost> fp)
			throws InterruptedException {
		while (posts.size() >= buffer)
			wait();
		posts.add(fp);
		notifyAll();
	}
	
	/**
	 * Blocks while there are no posts or the number of posts are too large.
	 */
	public synchronized List<ForumPost> getPost() throws InterruptedException {
		while (posts.isEmpty() && !finished())
			wait();
		notifyAll();
		if (posts.isEmpty())
			return null;
		return posts.poll();
	}

	public synchronized boolean finished() {
		return finished >= threads;
	}

	public synchronized void finish() {
		finished++;
		notifyAll();
	}

	public synchronized int size() {
		return posts.size();
	}
}
